<template>
  <div class="components-notice-add-or-update">
    <el-dialog
      v-model="visible"
      :title="$t('distributionMsg.announcementManagement')"
      :close-on-click-modal="false"
      width="60%"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="90px"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-form-item
          :label="$t('distributionMsg.whetherTop')"
          prop="msgType"
        >
          <el-radio-group v-model="dataForm.isTop">
            <el-radio :label="1">
              {{ $t("publics.yes") }}
            </el-radio>
            <el-radio :label="0">
              {{ $t("publics.no") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('text.startTime')"
          prop="startTime"
        >
          <el-date-picker
            v-model="dataForm.startTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            :placeholder="$t('marketing.chooseStartTime')"
            :disabled="pickerDisabled"
          />
        </el-form-item>
        <el-form-item
          :label="$t('text.endTime')"
          prop="endTime"
        >
          <el-date-picker
            v-model="dataForm.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            :placeholder="$t('marketing.chooseEndTime')"
            :disabled="pickerDisabled"
          />
        </el-form-item>
        <el-form-item
          :label="$t('distributionMsg.title')"
          prop="msgTitle"
        >
          <el-input
            v-model="dataForm.msgTitle"
            :placeholder="$t('distributionMsg.pleaseTitle')"
            controls-position="right"
            :min="0"
            :label="$t('distributionMsg.title')"
            maxlength="36"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          :label="$t('distributionMsg.content')"
          prop="content"
        >
          <tiny-mce
            v-if="visible"
            ref="tinyMceRef"
            v-model="dataForm.content"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t("remindPop.cancel") }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmit()"
          >
            {{ $t("remindPop.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import TinyMce from '@/components/tiny-mce/index.vue'
import { isHtmlNull, validHtmlLength } from '@/utils/index.js'

const emit = defineEmits(['refreshDataList'])

const dataForm = ref({
  time: [],
  msgId: 0,
  msgTitle: '',
  isTop: 0,
  content: '',
  pic: '',
  msgType: 0,
  state: 0,
  startTime: '',
  endTime: ''
})
const dataFormRef = ref(null)
const visible = ref(false)
const isSubmit = ref(false)
const pickerDisabled = ref(false)

// eslint-disable-next-line no-unused-vars
const validateTitle = (rule, value, callback) => {
  if (!value || !value.trim()) {
    callback(new Error($t('recruit.tipTitleTip1')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateContent = (rule, value, callback) => {
  if (isHtmlNull(value)) {
    callback(new Error($t('product.content')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  if (Date.parse(dataForm.value.startTime) >= Date.parse(dataForm.value.endTime)) {
    callback(new Error($t('coupon.validateTime')))
  } else {
    callback()
  }
}
const dataRule = {
  msgTitle: [
    { required: true, message: $t('recruit.tipTitleTip1'), trigger: 'blur' },
    { max: 255, message: $t('recruit.limitLangTip2'), trigger: 'blur' },
    { validator: validateTitle, trigger: 'blur' }
  ],
  content: [
    { required: true, message: $t('product.content'), trigger: 'blur' },
    { validator: validateContent, trigger: 'change' }
  ],
  startTime: [
    { required: true, message: $t('coupon.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('coupon.endTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ]
}

const init = (msgId) => {
  dataForm.value.msgId = msgId || 0
  visible.value = true
  isSubmit.value = false
  pickerDisabled.value = false
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.value.msgId) {
    getDataList()
  }
}

const tinyMceRef = ref(null)
const getDataList = () => {
  http({
    url: http.adornUrl(`/distribution/distributionMsg/info/${dataForm.value.msgId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
  })
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      const param = dataForm.value
      if (isSubmit.value) {
        return false
      }
      if (validHtmlLength(dataForm.value.content)) {
        return
      }
      if (dataForm.value.content && dataForm.value.content.length > 20000) {
        return ElMessage({
          message: $t('product.tinyMceTip'),
          type: 'error',
          duration: 1500
        })
      }
      isSubmit.value = true
      pickerDisabled.value = true
      http({
        url: http.adornUrl('/distribution/distributionMsg'),
        method: param.msgId ? 'put' : 'post',
        data: http.adornData(param)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            dataFormRef.value.resetFields()
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        pickerDisabled.value = true
        isSubmit.value = false
      })
    }
  })
}

defineExpose({
  init
})
</script>
